package com.java.method_reference;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 方法引用转变
 */
public class MethodReference {
    private String name;
    
    public MethodReference(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return name;
    }
    
    public static int reference(MethodReference o1, MethodReference o2) {
        return o1.name.compareTo(o2.name);
    }
    
    public static void main(String[] args) {
        List<MethodReference> list = new ArrayList();
        list.add(new MethodReference("MJQ"));
        list.add(new MethodReference("DCX"));
        list.add(new MethodReference("SYX"));
        list.add(new MethodReference("LYW"));
        list.add(new MethodReference("ZZY"));
        list.add(new MethodReference("YHX"));
        list.add(new MethodReference("HJL"));
        
        // 匿名内部类
        Collections.sort(list, new Comparator<MethodReference>() {
            @Override
            public int compare(MethodReference o1, MethodReference o2) {
                return o1.name.compareTo(o2.name);
            }
        });
        
        // lambda表达式：参数类型可省略、只有一个参数()可省略、方法体只有一句{};return可省略
        Collections.sort(list, (o1, o2) -> o1.name.compareTo(o2.name));
        
        // 方法引用
        Collections.sort(list, MethodReference::reference);
        
        System.out.println(list); // [DCX, HJL, LYW, MJQ, SYX, YHX, ZZY]
    }
}
